package com.example.blackmarket.module.SecondHandTrade.Shoplist;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.blackmarket.R;
import com.example.blackmarket.entities.SpacesItemDecoration;
import com.example.blackmarket.module.SecondHandTrade.ItemDetail.ItemDetailActivity;
import com.example.blackmarket.adapter.BuyinglistAdapter;
import com.example.blackmarket.entities.BuyingShopItem;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static android.app.Activity.RESULT_OK;
import static android.widget.AbsListView.OnScrollListener.SCROLL_STATE_IDLE;

public class BuyingFragment extends Fragment implements IShoplistView {
    private BuyinglistAdapter buyinglistAdapter;
    private ShoplistPresenter shoplistPresenter;
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private List<BuyingShopItem.ShopData> dataList = new ArrayList<>();
    private int pageNo=1;//当前数据加载到第几页
    private final int pageSize=20;
    private int typeId=1;//当前数据如何排序
    private int lastLoadDataItemPosition;//加载更多数据时最后一项是第几个数据
    private int listChange=1;
    static final int PICK_CONTACT_REQUEST = 1;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        shoplistPresenter = new ShoplistPresenter(BuyingFragment.this);
    }

    @Override
    public void onDestroy() {
        shoplistPresenter.detachView();
        super.onDestroy();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_buying,container,false);
        onBindView(view);
//        getData();
        return view;
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==PICK_CONTACT_REQUEST && resultCode==RESULT_OK){//request 0判断是该页面打开的详情页面，result 1代表详情页面发生了购买
            listChange=1;
        }
    }
    @Override
    public void onStart() {
        super.onStart();
        if(listChange==1){
            dataList.clear();
            getData();
            listChange=0;//重置code避免重复更新数据
        }
    }

    protected void onBindView(View view){
        recyclerView = view.findViewById(R.id.recycler_buy);
        layoutManager = new GridLayoutManager(getContext(),1);//1列布局
        recyclerView.setLayoutManager(layoutManager);
        //设置item边距
        HashMap<String, Integer> spacesValue = new HashMap<>();
        spacesValue.put(SpacesItemDecoration.TOP_SPACE, 10);
        spacesValue.put(SpacesItemDecoration.BOTTOM_SPACE, 20);
        spacesValue.put(SpacesItemDecoration.LEFT_SPACE, 20);
        spacesValue.put(SpacesItemDecoration.RIGHT_SPACE, 20);
        recyclerView.addItemDecoration(new SpacesItemDecoration(spacesValue));
        buyinglistAdapter = new BuyinglistAdapter(dataList,getContext());
        buyinglistAdapter.setOnItemClickListener(new BuyinglistAdapter.OnItemClickListener() { //设置点击item后的动作，在这里设置如何进入商品详情页
            @Override
            public void onItemClick(int position) {
                BuyingShopItem.ShopData item = dataList.get(position);
                Intent intent = new Intent(getActivity(), ItemDetailActivity.class);
                intent.putExtra("username", item.getNickname());
                intent.putExtra("areaNum",item.getCampus().equals("南校") ? 1 : 2);
                intent.putExtra("price",item.getShoppingGuidePrice());
                intent.putExtra("Image",item.getPictureAddress());
                //商品名
                intent.putExtra("item_id",item.getProductId());
                intent.putExtra("description",item.getShoppingGuideDescription());
                intent.putExtra("item_picture",item.getShoppingGuidePictureLocation());
                intent.putExtra("item_name",item.getShoppingGuideName());
                intent.putExtra("type",2);
                startActivityForResult(intent,PICK_CONTACT_REQUEST);
                //Toast.makeText(getContext(), "Click "+position,Toast.LENGTH_SHORT).show();
            }
        });
        setScrollNextPage();
        recyclerView.setAdapter(buyinglistAdapter);
    }

    @Override
    public void getData() {
        shoplistPresenter.getData(pageNo, typeId);
    }

    @Override
    public void showData(Object data) {
        BuyingShopItem buyingShopItem = (BuyingShopItem) data;
        dataList.addAll(buyingShopItem.getRecords());
        buyinglistAdapter.notifyDataSetChanged();
    }

    @Override
    public void showToast(String msg) {
        Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
    }

    protected void setScrollNextPage(){
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                /**
                 * 当下拉到当前列表最后一个商品时，请求并加载新的数据，届时可以通过item数量算出下一页的页码
                 */
                if (newState==SCROLL_STATE_IDLE && lastLoadDataItemPosition==buyinglistAdapter.getItemCount() && pageNo*pageSize==buyinglistAdapter.getItemCount()){
                    //在此加载下一页数据
                    ++pageNo;
                    getData();
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                if (layoutManager instanceof LinearLayoutManager){
                    int firstVisibleItemPosition = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
                    int lastVisibleItemPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
                    lastLoadDataItemPosition = firstVisibleItemPosition+(lastVisibleItemPosition-firstVisibleItemPosition)+1;
                }
            }
        });
    }
    public void setTypeId(int typeId){
        if(typeId!=this.typeId) {
            this.typeId = typeId;
            dataList.clear();
            getData();
        }
    }
}
